package cn.enited.devtools.apiaggregator.aspect;

import cn.enited.devtools.apiaggregator.anno.Lock;
import cn.enited.devtools.apiaggregator.exception.ExceptionHandler;
import cn.enited.devtools.apiaggregator.utils.RedissonUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class LockAspect {

    private ExceptionHandler exceptionHandler;

    private RedissonUtil redissonUtil;

    @Autowired
    public void setExceptionHandler(ExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    @Autowired
    public void setRedissonUtil(RedissonUtil redissonUtil) {
        this.redissonUtil = redissonUtil;
    }

    @Around(value = "@annotation(lockAnno)")
    public Object around(ProceedingJoinPoint point, Lock lockAnno) throws Throwable {
        Class<?> clazz = point.getTarget().getClass();
        MethodSignature signature = (MethodSignature) point.getSignature();
        String methodName = signature.getName();
        log.info("拦截到Lock注解方法：{}.{}", clazz.getName(), methodName);

        RLock lock = redissonUtil.getLock(lockAnno.name());
        try {
            lock.lock(lockAnno.lease(), lockAnno.unit());
            Object[] args = point.getArgs();
            return point.proceed(args);
        } catch (Throwable e) {
            log.error("Lock注解方法发生异常：", e);
            exceptionHandler.handleException(e);
        } finally {
            lock.unlock();
            log.info("=================Lock注解方法执行完毕=================");
        }
        return null;
    }
}
